import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import $axios from '../tools/axios'

export const useScheduleStore = defineStore('schedule', {
  state: () => {
    return {
      index: -1,
      dialogFormVisible: false,
      dialogFormTitle: '1234',
      trainno: 'g2604',
      tableData: [],
      /**
       * @type{sid :number, trainno: string,
        fromnm: string,
        tonm: string,
        waitfor: number,
        running: number,
        totime: string,
        ltime: string}
       * */
      formdata: {
        sid: -1,
        trainno: 'G',
        fromnm: '当前站点',
        tonm: '下一站',
        waitfor: 120,
        running: 60,
        totime: '12:12',
        ltime: '12:14'
      }
    }
  },
  // 也可以这样定义
  // state: () => ({ count: 0 })
  actions: {
    async modSchedule() {
      const path = '/s/mod'
      const { data: res } = await $axios.post(path, this.formdata)
      if (res.code === 200) {
        this.tableData.splice(this.index, 1, this.formdata)
        this.dialogFormVisible = false
      } else {
        ElMessage.error('Oops, this is a error message.')
      }
    },
    preInfo4Mdd(index, row) {
      this.index = index
      this.formdata = JSON.parse(JSON.stringify(row))
      this.dialogFormTitle = '编辑。。。。。'
      this.dialogFormVisible = true
    },

    async delSchedule(index, row) {
      const path = '/s/del/byid/' + row.sid
      const { data: res } = await $axios.delete(path)

      if (res.code === 200) {
        this.tableData.splice(index, 1)
        //
      }
    },

    async addSchedule() {
      const path = '/s/add'
      const { data: res } = await $axios.put(path, this.formdata)

      if (res.code === 200) {
        this.dialogFormVisible = false
        this.formdata.sid = res.data
        this.tableData.push(this.formdata)
      }
    },

    /**
     * 向服务器保存数据
     */
    save() {
      if (this.formdata.sid === -1) {
        this.addSchedule()
      } else {
        this.modSchedule()
      }
    },

    preInfo4Add() {
      this.formdata = JSON.parse(JSON.stringify(this.formdata)) //  clone
      this.formdata.sid = -1
      this.dialogFormTitle = `为 ${this.trainno} 提供新的列车时刻详情`
      this.formdata.trainno = this.trainno
      this.dialogFormVisible = true
    },

    async loadbyno() {
      this.tableData.length = 0
      console.log(this.trainno)
      const path = '/s/q/byno/' + this.trainno
      const { data: res } = await $axios.get(path)
      if (res.code === 200) {
        this.tableData = res.data
      }
      console.log(res)
    },
    /**
     * 加载数据
     */
    async loadall() {
      const path = '/s/q/all'
      const { data: res } = await $axios.get(path)
      if (res.code === 200) {
        this.tableData = res.data
      }
      console.log(res)
    }
  }
})
